<!DOCTYPE html>
<html lang="zh" xmlns:th="http://www.thymeleaf.org">
<head>
    <th:block th:include="include :: header('修改路由')"/>
    <th:block th:include="include :: select2-css"/>
</head>
<body>
<div class="main-content">
    <form id="form-route-edit" class="form-horizontal">
        <input hidden="hidden" th:field="${mongoRoute.id}">
        <h4 class="form-header h4">基本信息</h4>
        <div class="row">
            <div class="col-sm-10">
                <div class="form-group">
                    <label class="col-sm-4 control-label"><span style="color: red;">* </span> id (全局唯一)：</label>
                    <div class="col-sm-6">
                        <input placeholder="请输入路由 id" class="form-control" type="text" th:field="${mongoRoute.routeId}"
                               maxlength="64" required/>
                    </div>
                </div>
            </div>
        </div>
        <div class="row">
            <div class="col-sm-10">
                <div class="form-group">
                    <label class="col-sm-4 control-label"><span style="color: red;">* </span>uri：</label>
                    <div class="col-sm-6">
                        <input placeholder="请输入 uri" class="form-control" type="text" th:field="${mongoRoute.uri}"
                               maxlength="256" required/>
                    </div>
                </div>
            </div>
        </div>
        <div class="row">
            <div class="col-sm-10">
                <div class="form-group">
                    <label class="col-sm-4 control-label"> order：</label>
                    <div class="col-sm-6">
                        <input placeholder="请输入序号" class="form-control" type="number" th:field="${mongoRoute.order}"
                               value="0" min="0" step="1" max="6000"/>
                    </div>
                </div>
            </div>
        </div>
        <div class="row">
            <div class="col-sm-10">
                <div class="form-group">
                    <label class="col-sm-4 control-label"><span style="color: red;">* </span>predicates：</label>
                    <div class="col-sm-6">
                        <a class="btn btn-success" onclick="selectPredicates()">
                            <i class="fa fa-plus"></i> 添加
                        </a>
                        <p></p>
                        <p th:each="predicates : ${mongoRoute.predicates}" th:id="${predicates.name}">
                            [[${predicates.name}]]=<span th:each="mapArgs, mapIndex : ${predicates.args}"
                                                         th:text="${mapIndex.size > 1 ? mapIndex.count == mapIndex.size ? mapArgs.value : mapArgs.value + ',' : mapArgs.value}"></span>
                        </p>
                    </div>
                </div>
            </div>
        </div>
        <div class="row">
            <div class="col-sm-10">
                <div class="form-group">
                    <label class="col-sm-4 control-label">filters：</label>
                    <div class="col-sm-6">
                        <a class="btn btn-success" onclick="selectFilters()">
                            <i class="fa fa-plus"></i> 添加
                        </a>
                        <p></p>
                        <p th:each="filters : ${mongoRoute.filters}" th:id="${filters.name}">
                            [[${filters.name}]]=<span th:each="mapArgs, mapIndex : ${filters.args}"
                                                      th:text="${mapIndex.size > 1 ? mapIndex.count == mapIndex.size ? mapArgs.value : mapArgs.value + ',' : mapArgs.value}"></span>
                        </p>
                    </div>
                </div>
            </div>
        </div>

        <h4 class="form-header h4">其他信息</h4>
        <div class="row">
            <div class="col-sm-10">
                <div class="form-group">
                    <label class="col-sm-4 control-label">备注：</label>
                    <div class="col-sm-6">
                        <textarea name="remark" maxlength="500" class="form-control" rows="3"></textarea>
                    </div>
                </div>
            </div>
        </div>
    </form>
</div>

<div class="row">
    <div class="col-sm-offset-5 col-sm-10">
        <button type="button" class="btn btn-sm btn-primary" onclick="submitHandler()"><i class="fa fa-check"></i>保 存
        </button>&nbsp;
        <button type="button" class="btn btn-sm btn-danger" onclick="closeItem()"><i class="fa fa-reply-all"></i>关 闭
        </button>
    </div>
</div>
<th:block th:include="include :: footer"/>
<th:block th:include="include :: select2-js"/>
<script th:inline="javascript">

    $(document).ready(function () {

        let predicates = [[${mongoRoute.predicates}]];
        let filters = [[${mongoRoute.filters}]];

        // 断言隐藏域赋值
        let predicatesHtml = '';
        predicates.forEach(function (data) {
            let predicateArgs = data.args;
            let mapArgs = '';
            for (let key in predicateArgs) {
                mapArgs += predicateArgs[key] + ',';
            }
            mapArgs = mapArgs.slice(0, -1);
            predicatesHtml += '<input hidden="hidden" id="hidden' + data.name + '" name="predicates" value="' + data.name + '=' + mapArgs + '">';
        });
        $('#form-route-edit').append(predicatesHtml);

        // 过滤器隐藏域赋值
        let filtersHtml = '';
        filters.forEach(function (data) {
            let filterArgs = data.args;
            let mapArgs = '';
            for (let key in filterArgs) {
                mapArgs += filterArgs[key] + ',';
            }
            mapArgs = mapArgs.slice(0, -1);
            filtersHtml += '<input hidden="hidden" id="hidden' + data.name + '" name="filters" value="' + data.name + '=' + mapArgs + '">';
        });
        $('#form-route-edit').append(filtersHtml);

    });

    const prefix = ctx + "system/route";

    function submitHandler() {
        if ($('#form-route-edit').validate().form()) {
            let predicates = $('input[name="predicates"]').val();
            let filters = $('input[name="filters"]').val();
            if (undefined === predicates || null == predicates || '' === predicates) {
                // layer.alert("predicates 不能为空");
                $.modal.alertError("predicates 不能为空");
                // $.modal.msgError("predicates 不能为空");
                return;
            }
            let data = $("#form-route-edit").serializeArray();
            $.operate.saveTab(prefix + "/editRoute", data);
        }
    }

    /**
     * 选择断言
     */
    function selectPredicates() {
        const url = prefix + "/addPredicate";
        let options = {
            title: '选择 predicate',
            width: "800",
            url: url,
            callBack: doSubmitPredicate
        };
        $.modal.openOptions(options);
    }

    function doSubmitPredicate(index, layero) {
        // // 获取弹窗参数（方式一）
        // var body = layer.getChildFrame('body', index);
        // console.log(body.find('#id').val());
        // // 获取弹窗参数（方式二）
        // console.log($(layero).find("iframe")[0].contentWindow.document.getElementById("id").value);

        let contentWindow = layero.find("iframe")[0].contentWindow;
        let predicateName = contentWindow.$('#predicate-name').val();

        if (!contentWindow.$('#form-predicate-add').validate().form()) {
            return;
        }

        $('.col-sm-6:eq(3) p:eq(0)').remove();
        $('.col-sm-6:eq(3) a').after('<p></p>');
        $('#' + predicateName).remove();
        $('#hidden' + predicateName).remove();

        let html;
        switch (predicateName) {
            case 'Path':

                let patterns = contentWindow.$('input[name="patterns"]').val();

                html = '<input hidden="hidden" id="hidden' + predicateName + '" name="predicates" value="' + predicateName + '=' + patterns + '">' +
                    '<p id="' + predicateName + '">' + predicateName + '=' + patterns + '</p>';
                $('.col-sm-6:eq(3)').append(html);
                break;

            case 'Method':

                let methods = contentWindow.$('#methods').val()

                html = '<input hidden="hidden" id="hidden' + predicateName + '" name="predicates" value="' + predicateName + '=' + methods + '">' +
                    '<p id="' + predicateName + '">' + predicateName + '=' + methods + '</p>';
                $('.col-sm-6:eq(3)').append(html);
                break;

            case 'Query':

                let param = contentWindow.$('input[name="param"]').val();
                let regexp = contentWindow.$('input[name="regexp"]').val();

                html = '<input hidden="hidden" id="hidden' + predicateName + '" name="predicates" value="' + predicateName + '=' + param + '">' +
                    '<p id="' + predicateName + '">' + predicateName + '=' + param + '</p>';
                if (undefined !== regexp && null != regexp && '' !== regexp) {
                    html = '<input hidden name="predicates" value="' + predicateName + '=' + param + ',' + regexp + '">' +
                        '<p id="' + predicateName + '">' + predicateName + '=' + param + ',' + regexp + '</p>';
                }
                $('.col-sm-6:eq(3)').append(html);
                break;

            case 'Weight':

                let group = contentWindow.$('input[name="group"]').val();
                let weight = contentWindow.$('input[name="weight"]').val();

                html = '<input hidden="hidden" id="hidden' + predicateName + '" name="predicates" value="' + predicateName + '=' + group + ',' + weight + '">' +
                    '<p id="' + predicateName + '">' + predicateName + '=' + group + ',' + weight + '</p>';
                $('.col-sm-6:eq(3)').append(html);
                break;

            case 'MyCustom':

                let method = contentWindow.$('#method option:selected').val();

                html = '<input hidden="hidden" id="hidden' + predicateName + '" name="predicates" value="' + predicateName + '=' + method + '">' +
                    '<p id="' + predicateName + '">' + predicateName + '=' + method + '</p>';
                $('.col-sm-6:eq(3)').append(html);
                break;

            default:
                break;
        }

        layer.close(index);
    }

    /**
     * 选择过滤器
     */
    function selectFilters() {
        const url = prefix + "/addFilter";
        let options = {
            title: '选择 filter',
            width: "800",
            url: url,
            callBack: doSubmitFilter
        };
        $.modal.openOptions(options);
    }

    function doSubmitFilter(index, layero) {
        // // 获取弹窗参数（方式一）
        // var body = layer.getChildFrame('body', index);
        // console.log(body.find('#id').val());
        // // 获取弹窗参数（方式二）
        // console.log($(layero).find("iframe")[0].contentWindow.document.getElementById("id").value);

        let contentWindow = layero.find("iframe")[0].contentWindow;
        let filterName = contentWindow.$('#filter-name').val();
        if (!contentWindow.$('#form-filter-add').validate().form()) {
            return;
        }

        $('.col-sm-6:eq(4) p:eq(0)').remove();
        $('.col-sm-6:eq(4) a').after('<p></p>');
        $('#' + filterName).remove();
        $('#hidden' + filterName).remove();

        let html;
        switch (filterName) {
            case 'StripPrefix':

                let parts = contentWindow.$('input[name="parts"]').val();

                html = '<input hidden="hidden" id="hidden' + filterName + '" name="filters" value="' + filterName + '=' + parts + '">' +
                    '<p id="' + filterName + '">' + filterName + '=' + parts + '</p>';
                $('.col-sm-6:eq(4)').append(html);
                break;

            case 'MyCustom':

                let method = contentWindow.$('#method option:selected').val();

                html = '<input hidden="hidden" id="hidden' + filterName + '" name="filters" value="' + filterName + '=' + method + '">' +
                    '<p id="' + filterName + '">' + filterName + '=' + method + '</p>';
                $('.col-sm-6:eq(4)').append(html);
                break;

            default:
                break;
        }

        layer.close(index);
    }
</script>
</body>
</html>
